package com.ruoyi.web.controller.aggregation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.TokenManagementService;
import com.ruoyi.framework.security.TokenManagementService.AuthStats;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * Token管理Controller
 * 提供token刷新、踢出用户、统计等功能
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/agg/token")
public class TokenManageController
{
    @Autowired
    private TokenManagementService tokenManagementService;

    /**
     * 刷新当前用户token
     */
    @PostMapping("/refresh")
    public AjaxResult refreshToken(@RequestParam String token)
    {
        try {
            String newToken = tokenManagementService.refreshToken(token);
            if (newToken != null) {
                Map<String, String> result = new HashMap<>();
                result.put("token", newToken);
                return AjaxResult.success("token刷新成功", result);
            } else {
                return AjaxResult.error("token刷新失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("token刷新失败：" + e.getMessage());
        }
    }

    /**
     * 踢出指定用户（单点登录）
     */
    @PostMapping("/kick")
    public AjaxResult kickUser(@RequestParam Long userId)
    {
        try {
            tokenManagementService.kickUser(userId);
            return AjaxResult.success("用户已踢出");
        } catch (Exception e) {
            return AjaxResult.error("踢出用户失败：" + e.getMessage());
        }
    }

    /**
     * 将token加入黑名单
     */
    @PostMapping("/blacklist")
    public AjaxResult blacklistToken(@RequestParam String token)
    {
        try {
            tokenManagementService.blacklistToken(token);
            return AjaxResult.success("token已加入黑名单");
        } catch (Exception e) {
            return AjaxResult.error("加入黑名单失败：" + e.getMessage());
        }
    }

    /**
     * 清除当前用户缓存
     */
    @PostMapping("/clearCache")
    public AjaxResult clearCurrentUserCache()
    {
        try {
            Long userId = SecurityUtils.getUserId();
            if (userId == null) {
                return AjaxResult.error("用户未登录");
            }
            
            tokenManagementService.clearUserCache(userId);
            return AjaxResult.success("用户缓存已清除");
        } catch (Exception e) {
            return AjaxResult.error("清除缓存失败：" + e.getMessage());
        }
    }

    /**
     * 获取认证统计
     */
    @GetMapping("/stats")
    public AjaxResult getAuthStats(
            @RequestParam(defaultValue = "aggregation") String type,
            @RequestParam(required = false) String date)
    {
        try {
            if (date == null) {
                date = LocalDate.now().toString();
            }
            
            AuthStats stats = tokenManagementService.getAuthStats(type, date);
            
            Map<String, Object> result = new HashMap<>();
            result.put("date", date);
            result.put("type", type);
            result.put("successCount", stats.getSuccessCount());
            result.put("failureCount", stats.getFailureCount());
            result.put("totalCount", stats.getTotalCount());
            result.put("successRate", stats.getSuccessRate());
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近7天的认证统计
     */
    @GetMapping("/stats/week")
    public AjaxResult getWeekStats(@RequestParam(defaultValue = "aggregation") String type)
    {
        try {
            Map<String, AuthStats> weekStats = new HashMap<>();
            
            for (int i = 6; i >= 0; i--) {
                String date = LocalDate.now().minusDays(i).toString();
                AuthStats stats = tokenManagementService.getAuthStats(type, date);
                weekStats.put(date, stats);
            }
            
            return AjaxResult.success(weekStats);
        } catch (Exception e) {
            return AjaxResult.error("获取周统计失败：" + e.getMessage());
        }
    }
}